require 'iconv'

class ManageMyPaperController < ApplicationController
  before_filter :authorize, :except => :login
    before_filter   :configure_charsets
   layout "common_layout"
     
   
  def configure_charsets   
    @headers["Content-Type"]="text/html; charset=utf-8" 
  end  
  
  def list
    @paper_pages, @papers = paginate  :papers,:conditions => ['user_id = ?', session[:user_id]], :order => 'title DESC', :per_page => 10
  end
  
  def edit
    @paper = Paper.find(params[:id])
      if request.post?  
       @paper.title = params[:paper][:title] 
       @paper.author = params[:paper][:author] 
       @paper.publisher = params[:paper][:publisher] 
#       @paper.publish_time = params[:paper][:publish_time]
       @paper.paper_category_id=params[:paper][:paper_category_id]
       @paper.page_info = params[:paper][:page_info] 
        @paper.keyword1 = params[:paper][:keyword1] 
        @paper.keyword2 = params[:paper][:keyword2] 
         @paper.keyword3 = params[:paper][:keyword3] 
         @paper.download_url = params[:paper][:download_url] 
         @paper.abstract = params[:paper][:abstract] 
      if @paper.save
         flash.now[:notice] = "Change Information Successfully!"
      else
         flash.now[:notice] = "Have not Changed Registration Information !"
      end
     end
  end
  
  def delete    
     paper=Paper.find(params[:id])
     delete_file(paper.save_url)
     paper.destroy
     redirect_to :action => 'list'
  end
  
  def show
    @paper = Paper.find(params[:id])
  end
  
   def search
     
   end
   
  def delete_file(filename)
    File.delete("#{RAILS_ROOT}/uploadfile/#{filename}")
  end
  
  def upload_file(file)   
    if !file.original_filename.empty?   
      @filename=get_file_name(file.original_filename)
      File.open("#{RAILS_ROOT}/uploadfile/#{@filename}", "wb") do |f|   
        f.write(file.read)
      end   
      return @filename   
    end   
  end
  
  def download_file
    if params[:filename]
      send_file "#{RAILS_ROOT}/uploadfile/#{params[:filename]}"
    end
  end
  
  def get_file_name(filename)   
    if !filename.nil?   
      Time.now.strftime("%Y_%m_%d_%H_%M_%S") + '_' + Iconv.conv("gbk","utf-8",filename)  
    end   
  end   
end
